//
//  GMHFindDetailViewController.m
//  
//
//  Created by 郭明皓 on 15/10/26.
//
//

#import "GMHFindDetailViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
//#import "GMHSurroundModel.h"
#import "GMHsurroundDetailUrl.h"
#import "GMHSurroundDetailCell.h"
#import "GMHSellCell.h"
#import "GMHDataFiled.h"
#import "Sqlite.h"
#import "MBProgressHUD.h"
#import "DKNightVersion.h"
#import "GMH_Share.h"
#import "UMSocial.h"


@interface GMHFindDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableview;
@property (nonatomic, retain)UIView *headerView;
@property (nonatomic, retain)NSDictionary *detailDic;
@property (nonatomic, retain)NSArray *offerInfoArr;
@property (nonatomic, retain)NSArray *imageArr;
@property (nonatomic, retain)NSArray *weatherArr;
@property (nonatomic, retain)UIButton *collectbutton;


@end

@implementation GMHFindDetailViewController
- (void)dealloc
{
    [_collectbutton release];
    [_model release];
    [_weatherArr release];
    [_imageArr release];
    [_offerInfoArr release];
    [_tableview release];
    [_headerView release];
    [_detailDic release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    if ([GMH_Share SingleShare].isNight == YES) {
        self.view.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
    }
    else
    {
        self.view.backgroundColor = [UIColor whiteColor];
    }
    [self.tableview reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
    // Do any additional setup after loading the view.
    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    
    CGRect rect = CGRectMake(0, 0,
                             self.view.frame.size.width,
                             self.view.frame.size.height);
    //tableView创建
    self.tableview = [[UITableView alloc]initWithFrame:rect style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableview];
    [_tableview release];
    self.tableview.delegate = self;
    self.tableview.dataSource =self;;
//    self.tableview.rowHeight = 50;
    
    self.tableview.nightBackgroundColor = [UIColor blackColor];
    self.tableview.nightSeparatorColor = [UIColor darkGrayColor];
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 200)];
    self.tableview.tableHeaderView = self.headerView;
    [_headerView release];

#pragma mark 添加收藏分享 按钮
    UIView *rightbutton = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    
    _collectbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_collectbutton
     setImage:[UIImage imageNamed:@"collect.png"] forState:UIControlStateNormal];
    _collectbutton.frame = CGRectMake(0, 0, 40, 40);
    [_collectbutton addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setImage:[UIImage imageNamed:@"fenxiang.png"] forState:UIControlStateNormal];
    shareButton.frame = CGRectMake(60, 0, 40, 40);
    [shareButton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    
    [rightbutton addSubview:_collectbutton];
    [rightbutton addSubview:shareButton];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:rightbutton]autorelease];

    
    [self create];
    [self history];
    
}



//历史记录
- (void)history
{
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *dbPath = [sandBox stringByAppendingPathComponent:@"History.db"];
    //建立数据库
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
    NSLog(@"%@", dbPath);
    //打开数据库
    if ([db open]) {
        NSString *createTable = [NSString stringWithFormat:@"create table if not exists History (Ids integer primary key,productId text, productName text, productTitleContent text, price text, tetailPrice text, mImageUrl blob, saledCount integer)"];
        NSString *sql = @"insert into History (productId, productName, productTitleContent, price, tetailPrice, mImageUrl, saledCount)values (?, ?, ?, ?, ?, ?, ?)";
        //执行更新操作
        [db executeUpdate:createTable];
        BOOL data = [db executeUpdate:sql, _model.productId, _model.productName, _model.productTitleContent, _model.price, _model.retailPrice, _model.mImageUrl, _model.saledCount];
        if (!data) {
            NSLog(@"收藏失败");
            NSString *deletesql = [NSString stringWithFormat:@"delete from History where productId = %@", _model.productId];
            [db executeUpdate:deletesql];
            
        }
        else
        {
            NSLog(@"收藏成功");
        }
        //关闭数据库
        [db close];
    }
}
#pragma mark 收藏功能
- (void)collection:(UIButton *)collectionButton
{
    if (_model != nil) {
        
    
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *dbPath = [sandBox stringByAppendingPathComponent:@"Mysqlites.db"];
//建立数据库
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
    NSLog(@"%@", dbPath);
    //打开数据库
    if ([db open]) {
        NSString *createTable = [NSString stringWithFormat:@"create table if not exists surroundtable (productId text primary key, productName text, productTitleContent text, price text, tetailPrice text, mImageUrl blob, saledCount integer)"];
        
        //执行更新操作
        [db executeUpdate:createTable];
        
        NSString *sql = @"insert into surroundtable (productId, productName, productTitleContent, price, tetailPrice, mImageUrl, saledCount)values (?, ?, ?, ?, ?, ?, ?)";
        
        //插入数据
        BOOL datas = [db executeUpdate:sql, _model.productId, _model.productName, _model.productTitleContent, _model.price, _model.retailPrice, _model.mImageUrl, _model.saledCount];
    
        if (!datas) {
                NSLog(@"收藏失败");
                NSString *deletesql = [NSString stringWithFormat:@"delete from surroundtable where productId = %@", _model.productId];
                [db executeUpdate:deletesql];
                collectionButton.selected = !collectionButton.selected;
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"已经取消收藏";
                [hud hide:YES afterDelay:1.0];
            hud.mode = MBProgressHUDModeText;//显示类型
                [_collectbutton setImage:[UIImage imageNamed:@"collect.png"] forState:UIControlStateNormal];
       
        }
        else
        {
                NSLog(@"收藏成功");
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"收藏成功";
                [hud hide:YES afterDelay:1.0];
            hud.mode = MBProgressHUDModeText;
                _collectbutton.selected = !_collectbutton.selected;
                [_collectbutton setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
           
            
        }
        //关闭数据库
        [db close];
        }
    }
}
#pragma mark 分享信息
- (void)share:(UIButton *)sharebutton
{
    NSLog(@"分享成功");
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5639a9fd67e58e5fad00119c"
                                      shareText:nil
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ, UMShareToEmail, UMShareToSms, UMShareToQzone, UMShareToWechatTimeline, UMShareToTencent,nil]
                                       delegate:nil];
}

- (void)create
{
    [GMHDataFiled isHaveFileDocument];
    [GMHDataFiled isHaveFileSurround];
    
    NSInteger number = [self.productIds integerValue];
    NSString *strurl = [NSString stringWithFormat:@"http://appapi.yaochufa.com/v2/Product/GetProductInfoById?system=android&machineCode=ffffffff-9317-02f2-ffff-fffff60c2478&productId=%ld&channel=xiaomimarket&version=4.3.1", (long)number];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        self.detailDic = dic[@"data"];

        self.offerInfoArr = [GMHSurroundModel baseModelArry:dic[@"data"][@"offerInfo"]];
        self.imageArr =  [GMHSurroundModel baseModelArry:dic[@"data"][@"imageList"]];
        self.weatherArr = [GMHSurroundModel baseModelArry:dic[@"data"][@"weatherInfo"][0][@"weather_Data"]];
        
        GMHSurroundModel *surround = self.imageArr[0];
        UIImageView *images = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
        [images sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://cdn5.jinxidao.com/%@", surround.url]]];
        [self.headerView addSubview:images];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width , 25)];
        [self.headerView addSubview:label1];
        label1.text = self.detailDic[@"productName"];
        label1.backgroundColor = [UIColor whiteColor];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 175, self.view.frame.size.width , 25)];
        [self.headerView addSubview:label2];
        label2.text = self.detailDic[@"appSubTitle"];
        label2.font = [UIFont systemFontOfSize:12];
        label2.backgroundColor = [UIColor whiteColor];
        
        
        
        [self.tableview reloadData];
        [self selectsql];
        
        if (_collectbutton.selected) {
            [_collectbutton setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
            
        }
        
        if ([GMH_Share SingleShare].isNight == YES) {
            self.headerView.backgroundColor = [UIColor blackColor];
            images.alpha = 0.4;
            label1.nightBackgroundColor = UIColorFromRGB(0x343434);
            label2.nightBackgroundColor = UIColorFromRGB(0x343434);
            label1.textColor = [UIColor darkGrayColor];
            label2.textColor = [UIColor darkGrayColor];
        }
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Surround/Titledetail.plist"];
        [NSKeyedArchiver archiveRootObject:dic toFile:CachesPath];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}
- (void)selectsql
{
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"111111%@", sandBox);
    NSString *dbPath = [sandBox stringByAppendingPathComponent:@"Mysqlites.db"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
    if ([db open]) {
    
        NSString *sql = @"select * from surroundtable";
        FMResultSet *slc = [db executeQuery:sql];
        while ([slc next]) {
            if ([_model.productId integerValue] == [slc intForColumn:@"productId"]) {
                _collectbutton.selected = YES;
            }
        }
        [db close];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 1.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
    static NSString *strs = @"tableView1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
    }
        if (self.offerInfoArr.count != 0) {
            [DKNightVersionManager addClassToSet:self.class];
            cell.nightBackgroundColor = UIColorFromRGB(0x343434);
            
            GMHSurroundModel *surround = self.offerInfoArr[indexPath.row];
            cell.textLabel.text = surround.flagTitle;
            cell.textLabel.backgroundColor = [UIColor colorWithRed:1 green:0.83 blue:0.43 alpha:1];
            cell.detailTextLabel.text = surround.flagMsg;
            return cell;
        }
        
    }
    
        if (indexPath.section == 1)  {
        static NSString *strs = @"tableView2";
        GMHSellCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
        if (!cell) {
            cell = [[GMHSellCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
        }
            if (self.detailDic.count != 0) {
                [DKNightVersionManager addClassToSet:self.class];
                cell.nightBackgroundColor = UIColorFromRGB(0x343434);
                
                
                if (self.detailDic.count > 0) {
                    cell.sellCount.text = [NSString stringWithFormat:@"已售%@", self.detailDic[@"saledCount"]];
                    cell.evalua.text = [NSString stringWithFormat:@"%@人评价", self.detailDic[@"commentCount"]];
                    cell.sellCount.textColor = [UIColor darkGrayColor];
                    cell.evalua.textColor = [UIColor darkGrayColor];
                    
                }
                return cell;
            }

        }
            if (indexPath.section == 2){
        static NSString *strs = @"tableView3";
        GMHSurroundDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
        if (!cell) {
            cell = [[GMHSurroundDetailCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
        }
                if (self.detailDic.count != 0) {
                    [DKNightVersionManager addClassToSet:self.class];
                    cell.nightBackgroundColor = UIColorFromRGB(0x343434);
                    GMHSurroundModel *surrond = self.weatherArr[indexPath.row];
                    if (self.detailDic.count > 0) {
                        cell.address.text = [NSString stringWithFormat:@"%@", self.detailDic[@"address"]];
                        cell.wather.text =[NSString stringWithFormat:@"%@   %@   %@", [surrond.date substringWithRange:NSMakeRange(3, 6)], surrond.temperature, surrond.weather];
                        cell.address.numberOfLines = 0;
                        cell.address.textColor = [UIColor darkGrayColor];
                        cell.wather.textColor = [UIColor darkGrayColor];
                    }
                    return cell;
                }
        

    }
    if (indexPath.section == 3)    {
       static NSString *strs = @"tableView4";
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
       if (!cell) {
           cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
       }
        [DKNightVersionManager addClassToSet:self.class];
        cell.nightBackgroundColor = UIColorFromRGB(0x343434);
        if (self.detailDic.count > 0) {
       cell.textLabel.text = @"出行路线";
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }
       return cell;
   }
    if (indexPath.section == 5) {
        static NSString *strs = @"tableView5";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
        }
        [DKNightVersionManager addClassToSet:self.class];
        cell.nightBackgroundColor = UIColorFromRGB(0x343434);
        if (self.detailDic.count > 0) {
        cell.textLabel.text = @"详情介绍";
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }
        return cell;
    }
    else
    {
        
        static NSString *strs = @"tableView6";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
        }
        [DKNightVersionManager addClassToSet:self.class];
        cell.nightBackgroundColor = UIColorFromRGB(0x343434);
        if (self.detailDic.count > 0) {
        cell.textLabel.text = @"购买须知";
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }
        return cell;
    }
        
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger number = [self.productIds integerValue];
    if (indexPath.section == 3) {
        GMHsurroundDetailUrl *url = [[GMHsurroundDetailUrl alloc]init];
        [self.navigationController pushViewController:url animated:YES];
        [url release];

        url.url = self.detailDic[@"trafficGuide"];
         url.number = number;
    }
    if (indexPath.section == 5) {
        GMHsurroundDetailUrl *url = [[GMHsurroundDetailUrl alloc]init];
        [self.navigationController pushViewController:url animated:YES];
        [url release];

        url.url = self.detailDic[@"productIntroduction"];
         url.number = number;
    }
    if (indexPath.section == 4) {
        GMHsurroundDetailUrl *url = [[GMHsurroundDetailUrl alloc]init];
        [self.navigationController pushViewController:url animated:YES];
        [url release];

        url.url = self.detailDic[@"packageDetial"];
         url.number = number;
    }
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
